package installer.base;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class InstallSite {

	private static JdbcTemplate jdbcTemplate;

	@BeforeClass
	public static void before() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("config/context/applicationContext.xml");
		jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
	}

	@Test
	public  void install() throws DataAccessException, IOException {
		// 创建表
		/*
		 * try { //String sql =
		 * "CREATE TABLE site (id varchar(9) NOT NULL ,name varchar(30) NOT NULL ,type enum('country','province','city','county') NOT NULL ,parent varchar(9) NOT NULL ,PRIMARY KEY(id));"
		 * ; jdbcTemplate.update(installSql); } catch (Exception e) {
		 * e.printStackTrace(); }
		 */

		// 插入各个城市
		URL url = InstallSite.class.getClassLoader().getResource("installer/base/sql.txt");
		System.out.println(url.getPath());
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(url.getPath()), "UTF-8"));
		String row;
		int count = 0;
		while ((row = br.readLine()) != null) {
			System.out.println(row);
			String[] sqlproperties = row.split(",");
			int length = sqlproperties.length;
			String sql = "insert into site(id,name,type,parent) values(?,?,?,?);";
			String id = sqlproperties[0];
			String type = sqlproperties[length - 1];
			String parent = null;
			if (type.equals("country")) {
				parent = "000000000";
			} else if (type.equals("province")) {
				parent = id.substring(0, 3) + "000000";
			} else if (type.equals("city")) {
				parent = id.substring(0, 5) + "0000";
			} else if (type.equals("county")) {
				parent = id.substring(0, 7) + "00";
			}
			System.out.println(type + ":" + parent);
			jdbcTemplate.update(sql, new Object[] { id, sqlproperties[length - 2], type, parent });
			count++;
		}
		System.out.println("Site has been installed successfully，total: " + count + " records！");
		br.close();
	}
}
